package com.wsoft.hr.pm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wsoft.bpm.query.mapping.ExtraBusinessDataQuery;
import com.wsoft.constant.redis.HrPmRedisKeyConstant;
import com.wsoft.constant.redis.RedisKeyConstant;
import com.wsoft.core.annotation.GetRedisCache;
import com.wsoft.core.exception.Asserts;
import com.wsoft.core.service.CommonFreemarkerService;
import com.wsoft.core.service.CommonMemberService;
import com.wsoft.core.service.RedisService;
import com.wsoft.core.utils.LoginUserUtil;
import com.wsoft.core.vo.MemberVO;
import com.wsoft.entity.BaseEntity;
import com.wsoft.hr.pm.dto.MemberTemplateDTO;
import com.wsoft.hr.pm.entity.*;
import com.wsoft.hr.pm.entity.sys.HrOrganizationEntity;
import com.wsoft.hr.pm.enums.*;
import com.wsoft.hr.pm.manager.*;
import com.wsoft.hr.pm.mapper.HrPmMemberTemplateMapper;
import com.wsoft.hr.pm.query.activity.member.MemberQuery;
import com.wsoft.hr.pm.query.activity.member.template.*;
import com.wsoft.hr.pm.query.activity.member.template.scope.MemberTemplateScopeUpdateQuery;
import com.wsoft.hr.pm.query.activity.member.template.target.his.MemberTemplateSaveBatchQuery;
import com.wsoft.hr.pm.query.activity.member.template.target.his.MemberTemplateTargetHisUpdateQuery;
import com.wsoft.hr.pm.service.*;
import com.wsoft.hr.pm.service.sys.IHrOrganizationService;
import com.wsoft.hr.pm.vo.member.template.*;
import com.wsoft.hr.pm.vo.member.template.score.MemberTemplateScopeScoreVO;
import com.wsoft.hr.pm.vo.member.template.score.MemberTemplateScoreVO;
import com.wsoft.hr.pm.vo.process.activity.ProcessActivityNodeVO;
import com.wsoft.hr.pm.vo.template.TemplateVO;
import com.wsoft.vo.LoginUserVO;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 人员考核活动表 服务实现类
 * </p>
 *
 * @author zhanggukai
 * @since 2025年02月28日 09:21:31
 */
@Service
public class HrPmMemberTemplateServiceImpl extends ServiceImpl<HrPmMemberTemplateMapper, HrPmMemberTemplateEntity> implements IHrPmMemberTemplateService {

    @Resource
    private IHrOrganizationService hrOrganizationService;

    @Resource
    private HrPmMemberTemplateManager memberTemplateManager;

    @Resource
    private HrPmActivityManager activityManager;

    @Resource
    private IHrPmActivityService activityService;


    @Resource
    private IHrPmTemplateService templateService;

    @Resource
    private HrPmMemberTemplateScopeManager memberTemplateScopeManager;

    @Resource
    private HrPmTargetManager targetManager;

    @Resource
    private HrPmMemberTemplateTargetHisManager memberTemplateTargetHisManager;

    @Resource
    private IHrPmMemberTemplateScoreService memberTemplateScoreService;


    @Resource
    private IHrPmMemberTemplateTargetScoreService memberTemplateTargetScoreService;


    @Resource
    private HrPmMemberTemplateTargetManager memberTemplateTargetManager;

    @Resource
    private IHrPmProcessActivityService processActivityService;

    @Resource
    private IHrPmCycleService cycleService;

    @Resource
    private HrPmWarningManager warningManager;

    @Resource
    private CommonFreemarkerService freemarkerService;

    @Resource
    private CommonMemberService commonMemberService;

    @Resource
    private HrPmMemberTemplateScoreManager memberTemplateScoreManager;

    @Resource
    private RedisService redisService;

    @Resource
    private HrPmMemberTemplateMapper memberTemplateMapper;

    /**
     * 模版code
     */
    private final String FREEMARKER_CODE = "hr-data-exception-warning";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insert(MemberTemplateInsertQuery query) {
        HrPmMemberTemplateEntity entity = Convert.convert(HrPmMemberTemplateEntity.class, query);
        //校验考核人员重复
        List<HrPmMemberTemplateEntity> memberTemplateByQuery = memberTemplateManager.getMemberTemplateByQuery(query.getActivityId(), query.getMemberId());
        if (!memberTemplateByQuery.isEmpty()) {
            Asserts.fail("[hr.pm.member.template.exist]");
        }
        //校验考核人员重复
        HrPmActivityEntity activity = activityService.get(query.getActivityId());
        MemberQuery memberQuery = new MemberQuery();
        memberQuery.setMemberId(query.getMemberId());
        MemberTemplateQuery memberTemplateQuery = new MemberTemplateQuery();
        TemplateQuery templateQuery = new TemplateQuery();
        templateQuery.setTemplateId(query.getTemplateId());
        memberTemplateQuery.setTemplate(templateQuery);
        memberTemplateQuery.setMemberList(CollUtil.newArrayList(memberQuery));
        activityManager.checkCycle(activity.getCycleId(), CollUtil.newArrayList(memberTemplateQuery));
        entity.setState(HrProcessFlowStageEnum.MAKE_TARGET.getType());
        entity.setScoreStatus(0);
        entity.setTargetStatus(0);
        entity.setHrOrgFullName(getFullOrgName(entity.getHrOrgId()));
        boolean save = save(entity);
        if (save) {
            //查询出模版
            TemplateVO templateDetail = templateService.getTemplateDetail(entity.getTemplateId());
            String jsonString = JSONObject.toJSONString(templateDetail);
            MemberTemplateSaveQuery saveQuery = JSONObject.parseObject(jsonString, MemberTemplateSaveQuery.class);
            saveQuery.setId(entity.getId());
            convertTemplate(saveQuery);
            // 复制考评模版到考核活动
            processActivityService.copyTemplate(entity.getTemplateId(), entity.getId());
        }
        return save;
    }

    @Override
    public void saveBatchMemTemplate(MemberTemplateSaveBatchQuery query) {
        activityManager.saveBatchMemberTemplate(query.getActivityId(),query.getMemberTemplateList());
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        //删除模板
        removeById(id);

        //删除模版下流程
        List<HrPmMemberTemplateScopeEntity> scopeList = memberTemplateScopeManager.getByMemberTemplateId(id);
        List<Long> scopeIdList = scopeList.stream().map(BaseEntity::getId).collect(Collectors.toList());
        memberTemplateScopeManager.removeByIds(scopeIdList);

        //删除流程及以下 指标
        removeScope(scopeIdList);

        removeMemberTemplateRedisInfo(id);
        return true;
    }

    @Override
    public MemberTemplateRespVO getDetailTop(Long id) {
        HrPmMemberTemplateEntity entity = getById(id);
        MemberTemplateRespVO convert = Convert.convert(MemberTemplateRespVO.class, entity);
        HrPmActivityEntity activity = activityService.get(entity.getActivityId());
        convert.setActivityName(activity.getName());
        HrPmCycleEntity cycle = cycleService.getById(activity.getCycleId());
        convert.setExpireDate(cycle.getExpireDate());
        convert.setRange(cycle.getName() + "(" + cycle.getBeginDate() + "-" + cycle.getEndData() + ")");
        return convert;
    }

    @Override
    public PageInfo<HrPmMemberTemplateEntity> listMemberTemplate(MemberTemplateListQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<HrPmMemberTemplateEntity> list = memberTemplateManager.list(query);
        return PageInfo.of(list);
    }

    @Override
    @GetRedisCache(type = HrPmRedisKeyConstant.MEMBER_TEMPLATE_DETAIL_INFO,
            expire_sec = HrPmRedisKeyConstant.EXPIRED,
            value = RedisKeyConstant.REDIS_SELF)
    public MemberTemplateVO getMemberTemplateDetail(Long memberTemplateId) {
        MemberTemplateVO memberTemplateVO = new MemberTemplateVO();
        memberTemplateVO.setId(memberTemplateId);
        //获取人员模版流程信息
        returnScopeInfo(memberTemplateVO);
        //获取人员模版流程下的指标信息
        returnTargetInfo(memberTemplateVO.getScopeList());
        return memberTemplateVO;
    }

    @Override
    public MemberTemplateVO getMemberTemplateScoreDetail(Long memberTemplateId) {
        IHrPmMemberTemplateService proxy = (IHrPmMemberTemplateService) AopContext.currentProxy();
        MemberTemplateVO memberTemplateVO = proxy.getMemberTemplateDetail(memberTemplateId);
        HrPmMemberTemplateEntity memberTemplate = getById(memberTemplateId);
        memberTemplateVO.setScoreStatus(memberTemplate.getScoreStatus());
        //获取人员模版流程得分信息
        returnTargetScoreInfo( memberTemplate,memberTemplateVO.getScopeList());
        return memberTemplateVO;
    }


    @Override
    public PageInfo  pagePersonMemberTemplate(PersonListQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<MemberTemplateDTO> memberTemplateList = memberTemplateMapper.pagePersonList(query.getName(), query.getCycleId(), LoginUserUtil.getUserInfo().getLoginUserVO().getId());
        PageInfo pageInfo = PageInfo.of(memberTemplateList);
                List<MemberTemplateDTO> dataList = pageInfo.getList();
        List<String> businessCodes = dataList.stream().map(MemberTemplateDTO::getTargetBusinessCode).collect(Collectors.toList());
            List<ProcessActivityNodeVO> processActivityNode = processActivityService.getProcessActivityNode(businessCodes);
        List<PersonTemplateVO> result = new ArrayList<>();
                if (CollUtil.isNotEmpty(dataList)) {
                    dataList.forEach(item -> {
                        PersonTemplateVO convert = Convert.convert(PersonTemplateVO.class, item);
                        convert.setMemberTemplateId(item.getId());
                        convert.setHasScore(checkScore(item.getId()));
                        if (CollUtil.isNotEmpty(processActivityNode)){
                            Map<String, List<String>> map = processActivityNode.stream().collect(Collectors.toMap(ProcessActivityNodeVO::getBusinessKey, ProcessActivityNodeVO::getAssignList));
                            if (CollUtil.isNotEmpty(map.get(item.getTargetBusinessCode()))){
                                convert.setCurrentNode(String.join(",", map.get(item.getTargetBusinessCode())));
                            }
                        }
                        result.add(convert);
                    });
                }
                pageInfo.setList(result);
                return pageInfo;
            }

    @Override
    public PageInfo pageParticipateMemberTemplate(PersonListQuery query) {
        List<Long> ids = new ArrayList<>();
            Long memberId = LoginUserUtil.getUserInfo().getLoginUserVO().getId();
            //参与的自评数据
            QueryWrapper<HrPmMemberTemplateTargetHisEntity> targetHisQuery = new QueryWrapper<>();
            targetHisQuery.lambda().and(wrapper ->
                    wrapper.nested(nestedWrapper-> {
                        nestedWrapper.eq(HrPmMemberTemplateTargetHisEntity::getIsFormula, 0)
                                .eq(HrPmMemberTemplateTargetHisEntity::getResultScoreMemberValue, memberId.toString());
                    }).or(nestedWrapper->
                                nestedWrapper.eq(HrPmMemberTemplateTargetHisEntity::getIsFormula,1)
                                            .eq(HrPmMemberTemplateTargetHisEntity::getResultScoreMemberValue,memberId.toString())
                            )
            );
            List<HrPmMemberTemplateTargetHisEntity> targetHisList = memberTemplateTargetHisManager.list(targetHisQuery);
            if (CollUtil.isNotEmpty(targetHisList)){
                ids = targetHisList.stream().map(HrPmMemberTemplateTargetHisEntity::getMemberTemplateId).collect(Collectors.toList());
            }
            //参与的其他评分数据
            QueryWrapper<HrPmMemberTemplateScoreEntity> scoreQuery = new QueryWrapper<>();
            scoreQuery.lambda().eq(HrPmMemberTemplateScoreEntity::getScoreMemberId, memberId);
            List<HrPmMemberTemplateScoreEntity> scoreList = memberTemplateScoreService.list(scoreQuery);
            List<Long> collect = scoreList.stream().map(HrPmMemberTemplateScoreEntity::getMemberTemplateId).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(collect)){
                List<HrPmMemberTemplateEntity> memberTemplateEntities = memberTemplateManager.listByIds(collect);
                List<Long> memberTemplateIds = memberTemplateEntities.stream().filter(e -> e.getState().equals(HrProcessFlowStageEnum.COMPLETED.getType())).map(BaseEntity::getId).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(memberTemplateIds)){
                    ids.addAll(memberTemplateIds);
                }
            }
            ids = ids.stream().distinct().collect(Collectors.toList());
            if (CollUtil.isNotEmpty(ids)) {
                PageHelper.startPage(query.getPageNum(), query.getPageSize());
                //参与的考核活动数据
                List<MemberTemplateDTO> entityList = memberTemplateMapper.pageParticipateList(query.getName(), query.getCycleId(), ids);
                PageInfo pageInfo = PageInfo.of(entityList);
                List<MemberTemplateDTO> dataList = pageInfo.getList();
                List<PersonTemplateVO> result = new ArrayList<>();
                List<String> businessCodes = dataList.stream().map(MemberTemplateDTO::getTargetBusinessCode).collect(Collectors.toList());
                List<ProcessActivityNodeVO> processActivityNode = processActivityService.getProcessActivityNode(businessCodes);
                if (CollUtil.isNotEmpty(dataList)) {
                    dataList.forEach(item -> {
                        PersonTemplateVO convert = Convert.convert(PersonTemplateVO.class, item);
                        convert.setMemberTemplateId(item.getId());
                        convert.setHasScore(checkScore(item.getId()));
                        convert.setMemberId(item.getMemberId());
                        if (CollUtil.isNotEmpty(processActivityNode)){
                            Map<String, List<String>> map = processActivityNode.stream().collect(Collectors.toMap(ProcessActivityNodeVO::getBusinessKey, ProcessActivityNodeVO::getAssignList));
                            if (CollUtil.isNotEmpty(map.get(item.getTargetBusinessCode()))){
                                convert.setCurrentNode(String.join(",", map.get(item.getTargetBusinessCode())));
                            }
                        }
                        result.add(convert);
                    });
                }
                pageInfo.setList(result);
                return pageInfo;
            }
        return PageInfo.of(new ArrayList<>());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMemberTemplate(MemberTemplateSaveQuery query) {
        HrPmMemberTemplateEntity memberTemplate = getById(query.getId());
        //校验 权重等数据
        checkMemberTemplate(query);
        //编制状态允许修改
        if (memberTemplate.getTargetStatus()!=0){
           Asserts.fail("[hr.status.save.error]");
        }
        handleSave(query, false);
        removeMemberTemplateRedisInfo(query.getId());
        if (query.getIsSubmit()) {
            //调整现将工作流状态置为0
            if (memberTemplate.getState().equals(HrProcessFlowStageEnum.PERFORMANCE_SCORE.getType())){
                memberTemplateManager.update(Wrappers
                        .lambdaUpdate(HrPmMemberTemplateEntity.class)
                        .set(HrPmMemberTemplateEntity::getTargetStatus, 0)
                        .set(HrPmMemberTemplateEntity::getState, HrProcessFlowStageEnum.CHECK_TARGET.getType())
                        .eq(BaseEntity::getId, query.getId()));
            }
            else {
                String randomString = RandomUtil.randomString(8);
                memberTemplateManager.update(Wrappers
                        .lambdaUpdate(HrPmMemberTemplateEntity.class)
                        .set(HrPmMemberTemplateEntity::getTargetBusinessCode, randomString)
                        .set(HrPmMemberTemplateEntity::getState, HrProcessFlowStageEnum.CHECK_TARGET.getType())
                        .eq(BaseEntity::getId, query.getId()));
            }
            WorkFlowBusinessDataEnum checkTarget = WorkFlowBusinessDataEnum.TEMPLATE_DETAIL;
            ExtraBusinessDataQuery extraBusinessDataQuery = new ExtraBusinessDataQuery(checkTarget.getBusinessType(), checkTarget.getBusinessValue(), null, null);
            processActivityService.startProcess(query.getId(), HrProcessFlowStageEnum.CHECK_TARGET, extraBusinessDataQuery);
        }
    }

    @Override
    public void tempSaveMemberTemplate(MemberTemplateSaveQuery query) {
        handleSave(query, false);
        removeMemberTemplateRedisInfo(query.getId());
        //将审批状态置为草稿
        HrPmMemberTemplateEntity memberTemplate = getById(query.getId());
        if (memberTemplate.getTargetStatus()!=0){
            Asserts.fail("[hr.status.save.error]");
        }
        memberTemplate.setTargetStatus(0);
        updateById(memberTemplate);
    }

    @Override
    public PageInfo pageMemberTarget(MemberTemplateListQuery query) {
        List<HrPmMemberTemplateEntity> list = memberTemplateManager.list(query);
        Map<Long, HrPmMemberTemplateEntity> memberTemplateMap = list.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));
        if (CollUtil.isEmpty(list)){
            return PageInfo.of(new ArrayList<>());
        }
        List<Long> ids = list.stream().map(BaseEntity::getId).collect(Collectors.toList());
        List<HrPmMemberTemplateScopeEntity> scopeEntityList = memberTemplateScopeManager.getByMemberTemplateIds(ids);
        if (CollUtil.isEmpty(scopeEntityList)){
            return PageInfo.of(new ArrayList<>());
        }
        List<Long> scopeIdList = scopeEntityList.stream().map(BaseEntity::getId).collect(Collectors.toList());
        Map<Long, String> scopeMap = scopeEntityList.stream().collect(Collectors.toMap(BaseEntity::getId, HrPmMemberTemplateScopeEntity::getName));
        // 分页查询目标列表
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<HrPmMemberTemplateTargetEntity> targetList = memberTemplateTargetManager.getByScopeIds(scopeIdList);
        PageInfo pageInfo = PageInfo.of(targetList);
        List<HrPmMemberTemplateTargetEntity> pageInfoList = pageInfo.getList();
        List<Long> hisIds = pageInfoList.stream().map(HrPmMemberTemplateTargetEntity::getMemberTemplateTargetHisId).collect(Collectors.toList());
        List<HrPmMemberTemplateTargetHisEntity> entities = memberTemplateTargetHisManager.listByIds(hisIds);
        Map<Long, HrPmMemberTemplateTargetHisEntity> hisIdMap = entities.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));
        // 转换为目标VO列表
        List<MemberTemplateTargetVO> targetVoList = pageInfoList.stream().map(targetEntity -> {
            MemberTemplateTargetVO convert = Convert.convert(MemberTemplateTargetVO.class, memberTemplateMap.get(hisIdMap.get(targetEntity.getMemberTemplateTargetHisId()).getMemberTemplateId()));
            convert.setScopeId(targetEntity.getScopeId());
            convert.setTargetName(hisIdMap.get(targetEntity.getMemberTemplateTargetHisId()).getTargetName());
            convert.setWeight(targetEntity.getWeight());
            convert.setScopeName(scopeMap.get(targetEntity.getScopeId()));
            return convert;
        }).collect(Collectors.toList());
        // 返回分页结果
        pageInfo.setList(targetVoList);
        return  pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitScoreStage(Long memberTemplateId) {
        String randomString = RandomUtil.randomString(8);
        memberTemplateManager.update(Wrappers
                .lambdaUpdate(HrPmMemberTemplateEntity.class)
                .set(HrPmMemberTemplateEntity::getScoreBusinessCode, randomString)
                .set(HrPmMemberTemplateEntity::getState, HrProcessFlowStageEnum.PERFORMANCE_SCORE.getType())
                .eq(BaseEntity::getId, memberTemplateId));
        WorkFlowBusinessDataEnum checkTarget = WorkFlowBusinessDataEnum.SCORE_INDEX;
        ExtraBusinessDataQuery extraBusinessDataQuery = new ExtraBusinessDataQuery(checkTarget.getBusinessType(), checkTarget.getBusinessValue(), null, null);
        processActivityService.startProcess(memberTemplateId,
                HrProcessFlowStageEnum.PERFORMANCE_SCORE, extraBusinessDataQuery);
    }

    @Override
    public boolean updateState(MemberTemplateStateQuery query) {
        HrPmMemberTemplateEntity entity = Convert.convert(HrPmMemberTemplateEntity.class, query);
        HrPmMemberTemplateEntity memberTemplate = getById(query.getId());
        if (!memberTemplate.getMemberId().equals(LoginUserUtil.getUserInfo().getLoginUserVO().getId())){
            Asserts.fail("非自己的考核表无法确认！");
        }
        boolean b = updateById(entity);
        if (b){
            removeMemberTemplateRedisInfo(query.getId());
        }
        return b;
    }


    private String getFullOrgName(Long hrOrgId) {
        List<String> nameSegments = new ArrayList<>();
        List<HrOrganizationEntity> allOrg = hrOrganizationService.listAllHrOrgWithCache();
        //查询出总组织
        HrOrganizationEntity firstOrg = allOrg.stream().filter(e -> e.getPaId().equals(0L)).findFirst().get();
        Map<Long, HrOrganizationEntity> orgParentMap = allOrg.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));
        // 尝试循环加载组织配置
        do {
            nameSegments.add(orgParentMap.get(hrOrgId).getName());
            // 否则继续往上一级查找
            hrOrgId = orgParentMap.get(hrOrgId).getPaId();

        } while (hrOrgId.equals(firstOrg.getId()));
        // 反转顺序（从根到当前节点）
        Collections.reverse(nameSegments);
        return String.join("/", nameSegments);
    }

    /**
     * 处理保存方法
     *
     * @param query
     */
    private void handleSave(MemberTemplateSaveQuery query, boolean isCopy) {
        //处理模板流程表
        handleMemberTemplateScope(query.getId(), query.getScopeList());
        //处理模版指标和模版指标历史表
        for (MemberTemplateScopeUpdateQuery updateQuery : query.getScopeList()) {
            handleMemberTemplateTargetHis(query.getId(),updateQuery.getTemplateTargetHisList(), isCopy);
        }
        //移除指标表
        if (CollUtil.isNotEmpty(query.getRemoveTargetList())) {
            removeTargetHis(query.getRemoveTargetList());
        }
        //移除流程
        if (CollUtil.isNotEmpty(query.getRemoveScopeList())) {
            removeScope(query.getRemoveScopeList());
        }
    }

    /**
     * 处理模板流程表
     *
     * @param memberTemplateId
     * @param scopeList
     */
    private void handleMemberTemplateScope(Long memberTemplateId, List<MemberTemplateScopeUpdateQuery> scopeList) {

        for (MemberTemplateScopeUpdateQuery item : scopeList) {
            item.setMemberTemplateId(memberTemplateId);
            //新增或修改
            HrPmMemberTemplateScopeEntity memberTemplateScopeEntity = Convert.convert(HrPmMemberTemplateScopeEntity.class, item);
            memberTemplateScopeEntity.setMemberTemplateId(memberTemplateId);
            memberTemplateScopeManager.saveOrUpdate(memberTemplateScopeEntity);

            if (CollUtil.isNotEmpty(item.getTemplateTargetHisList())) {
                //赋值模板流程id
                for (MemberTemplateTargetHisUpdateQuery targetHis : item.getTemplateTargetHisList()) {
                    targetHis.setMemberTemplateScopeId(memberTemplateScopeEntity.getId());
                    targetHis.setMemberTemplateId(memberTemplateId);
                }
            }
        }
    }

    /**
     * 处理人员模版指标表 和人员模版指标历史表
     *
     * @param memberTargetHisList
     */
    private void handleMemberTemplateTargetHis(Long memberTemplateId ,List<MemberTemplateTargetHisUpdateQuery> memberTargetHisList, Boolean isCopy) {
        LoginUserVO loginUserVO = LoginUserUtil.getUserInfo().getLoginUserVO();
        if (CollUtil.isEmpty(memberTargetHisList)) {
            return;
        }
        for (MemberTemplateTargetHisUpdateQuery item : memberTargetHisList) {
            Long targetId = item.getTargetId();
            HrPmTargetEntity entity = targetManager.getById(targetId);
            if (null == entity || 0 == entity.getEnableFlag() || null == entity.getStatus() || 2 != entity.getStatus()) {
                Asserts.fail("[hr.pm.temp.target.error]");
            }


            HrPmTargetEntity targetEntity = Convert.convert(HrPmTargetEntity.class, item);
            if (null == item.getTargetId()) {
                //新增个人指标
                targetEntity.setMemberId(loginUserVO.getId());
                targetEntity.setEnableFlag(1);
                targetEntity.setTargetType(TargetTypeEnum.REFERENCE.getType());
                targetEntity.setStatus(2);
                targetManager.save(targetEntity);
                targetId = targetEntity.getId();
            } else {
                //判断是否为个人指标,个人指标则修改
                HrPmTargetEntity pmTargetEntity = targetManager.getById(item.getTargetId());
                if (null != pmTargetEntity && null != pmTargetEntity.getMemberId()) {
                    //如果是个人指标 则是复制模板的时候 则新增
                    if (isCopy) {
                        targetEntity.setId(null);
                        targetEntity.setMemberId(loginUserVO.getId());
                        targetEntity.setEnableFlag(1);
                        targetEntity.setTargetType(TargetTypeEnum.REFERENCE.getType());
                        targetEntity.setStatus(2);
                        targetManager.save(targetEntity);
                        targetId = targetEntity.getId();
                    } else {
                        //不是复制模板的时候 则是修改
                        targetManager.updateById(targetEntity);
                    }
                }
            }

            HrPmMemberTemplateTargetHisEntity hisEntity = Convert.convert(HrPmMemberTemplateTargetHisEntity.class, entity);
            hisEntity.setId(item.getId());
            hisEntity.setWeight(item.getWeight());
            hisEntity.setPurposeValue(item.getPurposeValue());
            //赋值 his表的targetId
            hisEntity.setTargetId(targetId);
            hisEntity.setMemberTemplateId(item.getMemberTemplateId());
            HrPmMemberTemplateEntity memberTemplate = getById(memberTemplateId);
            if (item.getIsFormula() == 1) {
                hisEntity.setResultInputMemberValue(changeMemberId(memberTemplate.getMemberId(), item.getResultInputMemberType(), item.getResultInputMemberValue()));
            }
            if (item.getIsFormula() == 0) {
                hisEntity.setResultScoreMemberValue(changeMemberId(memberTemplate.getMemberId(), item.getResultScoreMemberType(), item.getResultScoreMemberValue()));
            }
            //新增或修改
            boolean b = memberTemplateTargetHisManager.saveOrUpdate(hisEntity);
            //指标预警
            if(b&&hisEntity.getId()!=null&&hisEntity.getIsKey()==1&&hisEntity.getPurposeValue()!=null){
                HrPmMemberTemplateTargetHisEntity keyTarget = memberTemplateTargetHisManager.getById(hisEntity.getId());
                if (keyTarget.getPurposeValue().equals(hisEntity.getPurposeValue())){
                        HrPmWarningEntity warning = new HrPmWarningEntity();
                        warning.setTitle(buildFreemarkerMap(memberTemplate,FREEMARKER_CODE));
                        warning.setType(WarningTypeEnum.DATA_EXCEPTION.getType());
                        warning.setHrOrgId(memberTemplate.getHrOrgId());
                        warning.setOpenType("component");
                        warning.setOpenPage("");
                        warningManager.save(warning);
                }
            }
            //查询出id
            HrPmMemberTemplateTargetEntity target = memberTemplateTargetManager.getByTargetHisId(hisEntity.getId());
            HrPmMemberTemplateTargetEntity memberTemplateTargetEntity = new HrPmMemberTemplateTargetEntity();
            memberTemplateTargetEntity.setId(null==target?null:target.getId());
            memberTemplateTargetEntity.setMemberTemplateTargetHisId(hisEntity.getId());
            memberTemplateTargetEntity.setScopeId(item.getMemberTemplateScopeId());
            memberTemplateTargetEntity.setWeight(item.getWeight());
            memberTemplateTargetEntity.setPurposeValue(item.getPurposeValue());
            memberTemplateTargetEntity.setSort(item.getSort());
            memberTemplateTargetManager.saveOrUpdate(memberTemplateTargetEntity);

            //新增的指标 需要在his标中赋值templateTargetId
            if (null == hisEntity.getMemberTemplateTargetId()) {
                hisEntity.setMemberTemplateTargetId(memberTemplateTargetEntity.getId());
                memberTemplateTargetHisManager.updateById(hisEntity);
            }
        }
    }

    /**
     * 删除流程及以下 指标
     *
     * @param scopeIdList
     */
    private void removeScope(List<Long> scopeIdList) {
        if (CollUtil.isEmpty(scopeIdList)) {
            return;
        }
        //流程下的指标
        List<HrPmMemberTemplateTargetEntity> templateTargetList = memberTemplateTargetManager.getByScopeIds(scopeIdList);

        //删除流程
        memberTemplateScopeManager.removeByIds(scopeIdList);

        if (CollUtil.isEmpty(templateTargetList)) {
            return;
        }
        List<Long> targetList = templateTargetList.stream().map(BaseEntity::getId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(targetList)) {
            memberTemplateScopeManager.removeByIds(targetList);
        }

        //指标历史
        List<Long> hisIdList = templateTargetList.stream().map(HrPmMemberTemplateTargetEntity::getMemberTemplateTargetHisId).collect(Collectors.toList());
        if(CollUtil.isNotEmpty(hisIdList)){
            memberTemplateTargetHisManager.removeByIds(hisIdList);
        }
    }

    /**
     * 删除 指标历史表id
     *
     * @param targetHisIdList
     */
    private void removeTargetHis(List<Long> targetHisIdList) {
        if (CollUtil.isEmpty(targetHisIdList)) {
            return;
        }
        List<HrPmMemberTemplateTargetHisEntity> list = memberTemplateTargetHisManager.listByIds(targetHisIdList);
        memberTemplateTargetHisManager.removeByIds(targetHisIdList);

        List<Long> targetIdList = list.stream().map(HrPmMemberTemplateTargetHisEntity::getMemberTemplateTargetId).collect(Collectors.toList());
        if (CollUtil.isEmpty(targetIdList)) {
            return;
        }
        if (CollUtil.isNotEmpty(targetIdList)) {
            memberTemplateTargetManager.removeByIds(targetIdList);
        }
    }

    /**
     * 返回人员模版维度信息
     *
     * @param memberTemplateVO
     */
    private void returnScopeInfo(MemberTemplateVO memberTemplateVO) {

        List<MemberTemplateScopeVO> scopeVOList = new ArrayList<>();

        //获取模版下的流程
        List<HrPmMemberTemplateScopeEntity> scopeList = memberTemplateScopeManager.getByMemberTemplateId(memberTemplateVO.getId());
        if (CollUtil.isEmpty(scopeList)) {
            memberTemplateVO.setScopeList(scopeVOList);
            return;
        }
        for (HrPmMemberTemplateScopeEntity scope : scopeList) {
            MemberTemplateScopeVO scopeVO = Convert.convert(MemberTemplateScopeVO.class, scope);
            scopeVOList.add(scopeVO);
        }
        memberTemplateVO.setScopeList(scopeVOList);
    }

    /**
     * 返回人员模版维度评分信息
     *
     * @param memberTemplateScoreVO
     */
    private void returnScopeScoreInfo (MemberTemplateScoreVO memberTemplateScoreVO) {

        List<MemberTemplateScopeScoreVO> scopeScoreVOList = new ArrayList<>();

        //获取模版下的流程
        List<HrPmMemberTemplateScopeEntity> scopeList = memberTemplateScopeManager.getByMemberTemplateId(memberTemplateScoreVO.getId());
        if (CollUtil.isEmpty(scopeList)) {
            memberTemplateScoreVO.setScopeList(scopeScoreVOList);
            return;
        }
        for (HrPmMemberTemplateScopeEntity scope : scopeList) {
            MemberTemplateScopeScoreVO scopeVO = Convert.convert(MemberTemplateScopeScoreVO.class, scope);
            scopeVO.setScopeId(scope.getId());
            scopeScoreVOList.add(scopeVO);
        }
        memberTemplateScoreVO.setScopeList(scopeScoreVOList);
    }

    /**
     * 获取人员模版维度下的指标信息
     *
     * @param scopeVOList
     */
    private void returnTargetInfo(List<MemberTemplateScopeVO> scopeVOList) {
        if (CollUtil.isEmpty(scopeVOList)) {
            return;
        }
        List<Long> scopeIdList = scopeVOList.stream().map(MemberTemplateScopeVO::getId).collect(Collectors.toList());
        //获取维度下的所有指标
        List<HrPmMemberTemplateTargetEntity> templateTargetList = memberTemplateTargetManager.getByScopeIds(scopeIdList);
        if (CollUtil.isEmpty(templateTargetList)) {
            return;
        }
        //key:维度id,value:维度下的指标list
        Map<Long, List<HrPmMemberTemplateTargetEntity>> targetMap = templateTargetList.stream().collect(Collectors.groupingBy(HrPmMemberTemplateTargetEntity::getScopeId));
        //所有指标id集合
        List<Long> templateTargetIdList = templateTargetList.stream().map(BaseEntity::getId).collect(Collectors.toList());
        List<HrPmMemberTemplateTargetHisEntity> hisList = memberTemplateTargetHisManager.getByMemberTemplateTargetId(templateTargetIdList);

        for (MemberTemplateScopeVO scopeVO : scopeVOList) {
            List<HrPmMemberTemplateTargetEntity> scopeTargetList = targetMap.get(scopeVO.getId());
            if (CollUtil.isEmpty(scopeTargetList)) {
                continue;
            }
            List<Long> scopeTargetIdList = scopeTargetList.stream().map(BaseEntity::getId).collect(Collectors.toList());
            //维度下的 指标历史集合
            List<HrPmMemberTemplateTargetHisEntity> scopehisList = hisList.stream().filter(item -> scopeTargetIdList.contains(item.getMemberTemplateTargetId())).collect(Collectors.toList());
            List<MemberTemplateTargetHisVO> hisVOList = scopehisList.stream().map(item -> Convert.convert(MemberTemplateTargetHisVO.class, item))
                    .collect(Collectors.toList());

            //判断能否修改权重==> 部门指标 默认有权重则不能修改,没有权重或者为0 则可以修改
            List<Long> targetIdList = hisVOList.stream().map(MemberTemplateTargetHisVO::getTargetId).collect(Collectors.toList());
            if (CollUtil.isEmpty(targetIdList)) {
                scopeVO.setTemplateTargetHisList(hisVOList);
            } else {
                List<HrPmTargetEntity> targetList = targetManager.listByIds(targetIdList);
                Map<Long, HrPmTargetEntity> orgTarMap = targetList.stream().collect(Collectors.toMap(HrPmTargetEntity::getId, Function.identity()));
                for (MemberTemplateTargetHisVO templateTargetHisVO : hisVOList) {
                    HrPmTargetEntity targetEntity = orgTarMap.get(templateTargetHisVO.getTargetId());
                    if (null != targetEntity.getMemberId()) {
                        //用户指标 允许编辑
                        templateTargetHisVO.setUpdateWeight(true);
                        templateTargetHisVO.setUpdateStandard(true);
                        templateTargetHisVO.setUpdateParTargetId(true);
                        templateTargetHisVO.setUpdateRemark(true);
                        templateTargetHisVO.setUpdateGroupId(true);
                    } else {
                        canUpdate(templateTargetHisVO,targetEntity);
                    }
                }
                scopeVO.setTemplateTargetHisList(hisVOList);
            }
        }
    }

    public void canUpdate(MemberTemplateTargetHisVO templateTargetHisVO,HrPmTargetEntity targetEntity){
        //权重
        if (null == targetEntity.getWeight() || targetEntity.getWeight().compareTo(BigDecimal.ZERO) == 0) {
            //部门指标 权重为空或者为0 则可以编辑
            templateTargetHisVO.setUpdateWeight(true);
        } else {
            templateTargetHisVO.setUpdateWeight(false);
        }
        //标准
        if(StrUtil.isBlank(targetEntity.getStandard())){
            templateTargetHisVO.setUpdateStandard(true);
        }else{
            templateTargetHisVO.setUpdateStandard(false);
        }

        if(null == targetEntity.getPTargetId()){
            //上级指标为空则可以编辑
            templateTargetHisVO.setUpdateParTargetId(true);
        }else{
            templateTargetHisVO.setUpdateParTargetId(false);
        }

        if(null == targetEntity.getGroupId()){
            //分组为空则可以编辑
            templateTargetHisVO.setUpdateGroupId(true);
        }else{
            templateTargetHisVO.setUpdateGroupId(false);
        }

        if(null == targetEntity.getRemark()){
            //备注为空则可以编辑
            templateTargetHisVO.setUpdateRemark(true);
        }else{
            templateTargetHisVO.setUpdateRemark(false);
        }
    }

    /**
     * 获取人员模版维度下的指标信息
     * @param scopeVOList
     */
    private void returnTargetScoreInfo(HrPmMemberTemplateEntity memberTemplate ,List<MemberTemplateScopeVO> scopeVOList){
        if(CollUtil.isEmpty(scopeVOList)){
            return;
        }
        for (MemberTemplateScopeVO scopeVO : scopeVOList) {
            List<MemberTemplateTargetHisVO> targethHisList = scopeVO.getTemplateTargetHisList();
            if (CollUtil.isEmpty(targethHisList)) {
                continue;
            }
            //查询指标分数
            QueryWrapper<HrPmMemberTemplateTargetScoreEntity> targetScoreQuery = new QueryWrapper<>();
            //自己评过的分
            targetScoreQuery.lambda().eq(HrPmMemberTemplateTargetScoreEntity::getMemberTemplateId,memberTemplate.getId());
            List<HrPmMemberTemplateTargetScoreEntity> selfTargetScoreList = memberTemplateTargetScoreService.list(targetScoreQuery);
            Map<Long, List<HrPmMemberTemplateTargetScoreEntity>> collect = selfTargetScoreList.stream().collect(Collectors.groupingBy(HrPmMemberTemplateTargetScoreEntity::getMemberTemplateTargetId));
            List<HrPmMemberTemplateScoreEntity> entityList = memberTemplateScoreManager.listMemberTemplateScore(memberTemplate.getId(), LoginUserUtil.getUserInfo().getLoginUserVO().getId());
            List<MemberTemplateTargetHisVO> hisVOList = targethHisList.stream().map(item ->{
                      return handleTarget(item,CollUtil.isEmpty(entityList) ? null : entityList.get(0).getId(), memberTemplate,collect);
                    })
                    .collect(Collectors.toList());
            scopeVO.setTemplateTargetHisList(hisVOList);
        }
    }

    /***
     * 模板保存校验
     * @param query
     */
    private void checkMemberTemplate(MemberTemplateSaveQuery query) {
        List<MemberTemplateScopeUpdateQuery> scopeList = query.getScopeList();
        if (CollUtil.isEmpty(scopeList)) {
            Asserts.fail("[hr.pm.weight.error]");
        }

        //判断维度是否有重复
        if(!isScopeIdUnique(scopeList)){
            Asserts.fail("[hr.pm.scope.repeat]");
        }

        //判断指标是否有重复
        if(!isTargetIdUnique(scopeList)){
            Asserts.fail("[hr.pm.target.repeat]");
        }

        BigDecimal scopeWeightAdd = scopeList.stream().map(MemberTemplateScopeUpdateQuery::getWeight).reduce(BigDecimal.ZERO, BigDecimal::add);
        //校验维度权重是否等于100
        checkWeight(scopeWeightAdd, BigDecimal.valueOf(100));

        //遍历判断 指标权重之和 是否等于维度权重
        for (MemberTemplateScopeUpdateQuery scope : scopeList) {
            List<MemberTemplateTargetHisUpdateQuery> hisList = scope.getTemplateTargetHisList();
            BigDecimal targetWeightAdd = hisList.stream()
                    // 过滤掉 weight 为 null 的项，并抛出异常或记录错误
                    .peek(item -> {
                        if (item.getWeight() == null) {
                            Asserts.fail("权重不能为空！");
                        }
                    })
                    //指标计算权重 不算 加减分项
                    .filter(item -> TargetTypeEnum.REFERENCE.getType().equals(item.getTargetType()))
                    .map(MemberTemplateTargetHisUpdateQuery::getWeight)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            checkWeight(targetWeightAdd, scope.getWeight());
        }

    }

    /**
     * 校验是否已评分
     *
     * @param memberTemplateId
     */
    private boolean checkScore(Long memberTemplateId) {
        QueryWrapper<HrPmMemberTemplateScoreEntity> scoreQuery = new QueryWrapper<>();
        scoreQuery.lambda().eq(HrPmMemberTemplateScoreEntity::getMemberTemplateId, memberTemplateId)
                .eq(HrPmMemberTemplateScoreEntity::getScoreMemberId, LoginUserUtil.getUserInfo().getLoginUserVO().getId());
        if (memberTemplateScoreService.count(scoreQuery) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 校验权重
     *
     * @param weight
     * @param standard
     */
    private void checkWeight(BigDecimal weight, BigDecimal standard) {
        if (weight.compareTo(standard) != 0) {
            Asserts.fail("[hr.pm.weight.error]");
        }
    }

    private String changeMemberId(Long memberId, String type, String value) {
        if (type.equals(ScoreMemberTypeEnum.OWNER.getType())) {
            return memberId.toString();
        }
        if (type.equals(ScoreMemberTypeEnum.LEADER.getType())) {
            MemberVO memberInfo = commonMemberService.getMemberInfo(memberId);
            if (memberInfo.getMemberLeaderId()==null){
                Asserts.fail("[联系管理员配置上级领导！");
            }
            return memberInfo.getMemberLeaderId().toString();
        }
        return value;
    }

    /**
     * 拷贝模版转换
     *
     * @param query
     */
    private void convertTemplate(MemberTemplateSaveQuery query) {
        List<MemberTemplateScopeUpdateQuery> scopeList = query.getScopeList();
        if (CollUtil.isNotEmpty(scopeList)) {
            for (MemberTemplateScopeUpdateQuery scopeUpdateQuery : scopeList) {
                scopeUpdateQuery.setId(null);
                List<MemberTemplateTargetHisUpdateQuery> hisList = scopeUpdateQuery.getTemplateTargetHisList();
                if (CollUtil.isNotEmpty(hisList)) {
                    for (MemberTemplateTargetHisUpdateQuery hisUpdateQuery : hisList) {
                        hisUpdateQuery.setId(null);
                    }
                }
            }
        }
        //复制模板
        handleSave(query, true);
    }


    @Override
    public void complete(String processDefKey, String processInstanceId, String businessKey) {
        HrPmMemberTemplateEntity entity = memberTemplateManager.getTargetByBusinessKey(businessKey);
        if (entity != null) {
            //修改状态
            entity.setState(HrProcessFlowStageEnum.PERFORMANCE_SCORE.getType());
            memberTemplateManager.updateById(entity);
        }
        IHrPmMemberTemplateService.super.complete(processDefKey, processInstanceId, businessKey);
    }

    @Override
    public String getProcessDefKey() {
        return HrProcessFlowStageEnum.CHECK_TARGET.getProcessDefKey();
    }

    /**
     * 使用 Stream 检查 List 中的 targetId 是否重复
     *
     * @param list 包含 TemplateTargetHisBaseQuery 对象的 List
     * @return 如果 targetId 没有重复，返回 true；否则返回 false
     */
    private boolean isTargetIdUnique(List<MemberTemplateScopeUpdateQuery> list){
        if (list == null || list.isEmpty()) {
            // 空列表或不包含元素，视为没有重复
            return true;
        }

        //获取所有维度中的指标
        List<MemberTemplateTargetHisUpdateQuery> targetHisList = new ArrayList<>();
        for (MemberTemplateScopeUpdateQuery updateQuery : list) {
            List<MemberTemplateTargetHisUpdateQuery> hisList = updateQuery.getTemplateTargetHisList();
            if(CollUtil.isNotEmpty(hisList)){
                targetHisList.addAll(hisList);
            }
        }
        //顺便校验 指标为系统计算的,必填目标值
        long count = targetHisList.stream().filter(item -> null != item.getIsFormula() && item.getIsFormula() == 1 && null == item.getPurposeValue()).count();
        if(count > 0){
            Asserts.fail("[hr.pm.purposeValue.error]");
        }


        long distinctCount = targetHisList.stream()
                // 过滤掉 null 对象和 null scopeId
                .filter(item -> item != null && item.getTargetId() != null)
                // 提取 scopeId
                .map(MemberTemplateTargetHisUpdateQuery::getTargetId)
                .distinct() // 去重
                .count(); // 计算去重后的数量

        long totalCount = targetHisList.stream()
                .filter(item -> item != null && item.getTargetId() != null)
                .count(); // 计算过滤后的总数
        // 如果去重后的数量等于总数，说明没有重复
        return distinctCount == totalCount;
    }

    /**
     * 使用 Stream 检查 List 中的 scopeId 是否重复
     *
     * @param list 包含 TemplateScopeBaseQuery 对象的 List
     * @return 如果 scopeId 没有重复，返回 true；否则返回 false
     */
    private boolean isScopeIdUnique(List<MemberTemplateScopeUpdateQuery> list) {
        if (list == null || list.isEmpty()) {
            // 空列表或不包含元素，视为没有重复
            return true;
        }
        long distinctCount = list.stream()
                // 过滤掉 null 对象和 null scopeId
                .filter(item -> item != null && item.getScopeId() != null)
                // 提取 scopeId
                .map(MemberTemplateScopeUpdateQuery::getScopeId)
                .distinct() // 去重
                .count(); // 计算去重后的数量

        long totalCount = list.stream()
                .filter(item -> item != null && item.getScopeId() != null)
                .count(); // 计算过滤后的总数
        // 如果去重后的数量等于总数，说明没有重复
        return distinctCount == totalCount;
    }
    /**
     * 构建freemarker模板
     * @param vo
     * @param freemarkerCode
     * @return
     */
    private String buildFreemarkerMap(HrPmMemberTemplateEntity vo,String freemarkerCode){
        Map<String,Object> map = new HashMap<>(3);
        map.put("memberName",vo.getMemberName());
        map.put("templateName",vo.getTemplateName());
        //${memberName}${templateName}的关键指标目标发生变更，请注意调整工作。
        return freemarkerService.sendTextTemplate(freemarkerCode, map, true);
    }

    @Override
    public void back(String processDefKey, String processInstanceId, String businessKey) {
        HrPmMemberTemplateEntity entity = memberTemplateManager.getTargetByBusinessKey(businessKey);
        if (entity != null) {
            //修改状态
            entity.setState(HrProcessFlowStageEnum.MAKE_TARGET.getType());
            memberTemplateManager.updateById(entity);
        }
        IHrPmMemberTemplateService.super.back(processDefKey, processInstanceId, businessKey);
    }


    /**
     * 移除人员模版缓存
     * @param id
     */
    private void removeMemberTemplateRedisInfo(Long id){
        if(null != id){
            redisService.del(HrPmRedisKeyConstant.MEMBER_TEMPLATE_DETAIL_INFO + id);
        }
    }

    /**
     * 处理指标能否修改 是否返回评分
     * @param item
     * @param memberTemplateScoreId
     * @param memberTemplate
     * @param collect
     * @return
     */
    private MemberTemplateTargetHisVO handleTarget(MemberTemplateTargetHisVO item, Long memberTemplateScoreId, HrPmMemberTemplateEntity memberTemplate, Map<Long, List<HrPmMemberTemplateTargetScoreEntity>> collect) {
        if (item.getIsFormula() == 1) {
            if (item.getResultInputMemberValue().equals(LoginUserUtil.getUserInfo().getLoginUserVO().getId().toString())) {
                item.setCurModified(memberTemplate.getScoreStatus() != 1);
                if (CollUtil.isNotEmpty(collect) && CollUtil.isNotEmpty(collect.get(item.getMemberTemplateTargetId()))) {
                    List<HrPmMemberTemplateTargetScoreEntity> scoreEntities = collect.get(item.getMemberTemplateTargetId()).stream()
                            .filter(e -> e.getMemberTemplateScoreId().equals(memberTemplateScoreId)).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(scoreEntities)) {
                        HrPmMemberTemplateTargetScoreEntity targetScoreEntity = scoreEntities.get(0);
                        item.setScore(targetScoreEntity.getScore());
                        item.setResultValue(targetScoreEntity.getResultValue());
                    }
                }
            } else {
                item.setCurModified(false);
                if (memberTemplate.getScoreStatus() != 0) {
//                                    if (item.getResultInputMemberValue().equals(memberTemplate.getMemberId().toString())){
//                                        convert.setCurModified(true);
//                                    }
//                                    else {
                    if (CollUtil.isNotEmpty(collect) && CollUtil.isNotEmpty(collect.get(item.getMemberTemplateTargetId()))) {
                        item.setScore(collect.get(item.getMemberTemplateTargetId()).get(0).getScore());
                        item.setResultValue(collect.get(item.getMemberTemplateTargetId()).get(0).getResultValue());
                    }
//                                    }
                }
            }
        }
        if (item.getIsFormula() == 0) {
            if (item.getResultScoreMemberValue().equals(LoginUserUtil.getUserInfo().getLoginUserVO().getId().toString())) {
                item.setCurModified(memberTemplate.getScoreStatus() != 1);
                if (CollUtil.isNotEmpty(collect) && CollUtil.isNotEmpty(collect.get(item.getMemberTemplateTargetId()))) {
                    List<HrPmMemberTemplateTargetScoreEntity> scoreEntities = collect.get(item.getMemberTemplateTargetId()).stream()
                            .filter(e -> e.getMemberTemplateScoreId().equals(memberTemplateScoreId)).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(scoreEntities)) {
                        HrPmMemberTemplateTargetScoreEntity targetScoreEntity = scoreEntities.get(0);
                        item.setScore(targetScoreEntity.getScore());
                    }
                }
            } else {
                if (item.getResultScoreMemberValue().equals(memberTemplate.getMemberId().toString())) {
                    item.setCurModified(false);
                    if (memberTemplate.getScoreStatus() == 1) {
                        item.setCurModified(true);
                    }
                } else {
                    item.setCurModified(false);
                    if (memberTemplate.getScoreStatus() != 0) {
                        if (CollUtil.isNotEmpty(collect) && CollUtil.isNotEmpty(collect.get(item.getMemberTemplateTargetId()))) {
                            item.setScore(collect.get(item.getMemberTemplateTargetId()).get(0).getScore());
                        }
                    }
                }
            }
        }
        return item;
    }
}
